/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.keygen.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

/** 
 * @author LiBo/Alex
 * @since TODO引入特定改变发布版本
 * @version V1.0 
 */
@Data
@AllArgsConstructor
@Builder
public final class GuidUtils {
    
    @Getter
    @Setter
    GuidRandom guidRandom;
    
    @Getter
    @Setter
    String systemCode;
    
    
    String wrapperByMessageDigest(String messageDigestType) throws NoSuchAlgorithmException {
        messageDigestType = messageDigestType == null?"MD5":messageDigestType;
        MessageDigest messageType = null;
        StringBuffer wrapperValue = new StringBuffer(128);
        messageType = MessageDigest.getInstance(messageDigestType);
        return messageDigestType;
    }
    
    //@Builder
    class GuidRandom{
       @Getter
       @Setter
       private Random keyRandom;
       @Getter
       @Setter
       private SecureRandom secureKeyRandom;
       
       public boolean init() throws UnknownHostException {
           try {
            secureKeyRandom = new SecureRandom();
            long secureInitializer = secureKeyRandom.nextLong();
            keyRandom = new Random(secureInitializer);
            InetAddress address = InetAddress.getLocalHost();
            systemCode = systemCode == null ? address == null ? "127.0.0.1" : 
                address.toString():systemCode;
        } catch (Exception e) {
            return false;
        }
           return true;
       }
       
       public boolean init(String systemCode) throws UnknownHostException {
           try {
            secureKeyRandom = new SecureRandom();
            long secureInitializer = secureKeyRandom.nextLong();
            keyRandom = new Random(secureInitializer);
        } catch (Exception e) {
            return false;
        }
           return true;
       }
    }

}
